import { message } from "antd";
import store from "@/redux";
import { setTagList } from "@/redux/modules/menu";
/**
 * 日期格式化
 *
 * @param {string} time 日期
 * @param {string} pattern 格式化类型
 * @returns
 */
export const parseTime = (time: string | number | Date, pattern: string) => {
  if (!time) {
    return null;
  }
  const format = pattern || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string" && /^[0-9]+$/.test(time)) {
      time = parseInt(time);
    } else if (typeof time === "string") {
      time = time.replace(new RegExp(/-/gm), "/");
    }
    // prettier-ignore
    if (typeof time === "number" && time.toString().length === 10) {
            time = time * 1000;
        }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  // prettier-ignore
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result: string | any[], key: string) => {
        let value = formatObj[key];
        // Note: getDay() returns 0 on Sunday
        if (key === "a") {
            return ["日", "一", "二", "三", "四", "五", "六"][value];
        }
        if (result.length > 0 && value < 10) {
            value = "0" + value;
        }
        return value || 0;
    });
  return time_str;
};

/**
 * 图片
 *
 */

export function getAssetsFile(url) {
  return new URL(`../assets/images/${url}.png`, import.meta.url).href;
}

/**
 * map 全局
 *
 */
export function MapLoader() {
  return new Promise((resolve, reject) => {
    if (window.AMap) {
      resolve(window.AMap);
    }
    window.initAMap = () => {
      resolve(window.AMap);
    };
  });
}

/**
 * 参数处理
 *
 * @param {*} params  参数
 */
export function tansParams(params: { [x: string]: any }) {
  let result = "";
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    var part = encodeURIComponent(propName) + "=";
    if (value !== null && value !== "" && typeof value !== "undefined") {
      if (typeof value === "object") {
        for (const key of Object.keys(value)) {
          // prettier-ignore
          if (value[key] !== null && value !== "" && typeof value[key] !== "undefined") {
                        let params = propName + "[" + key + "]";
                        var subPart = encodeURIComponent(params) + "=";
                        result += subPart + encodeURIComponent(value[key]) + "&";
                    }
        }
      } else {
        result += part + encodeURIComponent(value) + "&";
      }
    }
  }
  return result;
}

// 验证是否为blob格式
export const blobValidate = async (data: any) => {
  let b = false;
  try {
    const text = await data.text();
    JSON.parse(text);
    b = false;
  } catch (error) {
    b = true;
  }
  return b;
};

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
// prettier-ignore
export const handleTree = (data: any, id: any, parentId: any, children: any) => {
	let config = {
		id: id || "id",
		parentId: parentId || "parentId",
		childrenList: children || "children",
	};

	var childrenListMap = {};
	var nodeIds = {};
	var tree = [];

	for (let d of data) {
		let parentId = d[config.parentId];
		if (childrenListMap[parentId] == null) {
			childrenListMap[parentId] = [];
		}
		nodeIds[d[config.id]] = d;
		childrenListMap[parentId].push(d);
	}

	for (let d of data) {
		let parentId = d[config.parentId];
		if (nodeIds[parentId] == null) {
			tree.push(d);
		}
	}

	for (let t of tree) {
		adaptToChildrenList(t);
	}

	function adaptToChildrenList(o: { [x: string]: any; }) {
		if (childrenListMap[o[config.id]] !== null) {
			o[config.childrenList] = childrenListMap[o[config.id]];
		}
		if (o[config.childrenList]) {
			for (let c of o[config.childrenList]) {
				adaptToChildrenList(c);
			}
		}
	}
	return tree;
};

/**
 * 树型结构数据构造成一维数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
function TreeToArray(tree) {
  // 判断 tree 是否有值，无返回 []
  if (!Array.isArray(tree) || !tree.length) return [];
  let res = [];
  tree.forEach((v) => {
    // tree的每个元素都 放入到 res里面
    res.push(v);
    if (v.children) {
      // 有children 就把 children数据递归 返回  依次放到 res里面
      res.push(...TreeToArray(v.children));
    }
  });
  return res;
}

/**
 * 递归查询对应的路由
 * @param {*} path 当前访问地址
 * @param {*} routes 路由列表
 */

export const searchRoute = (path: string, routes) => {
  let result = {};
  for (let item of routes) {
    if (item.path === path) return item;
    if (item.children) {
      const res = searchRoute(path, item.children);
      if (Object.keys(res).length) result = res;
    }
  }
  return result;
};

/**
 * 全局loading
 * @param {*} content 加载的提示词
 * @param {*} duration 延时时间，默认不关闭
 */
export const modalLoading = (content = "请稍候...", duration = 0) => {
  return message.loading({
    content: content,
    duration: duration,
    className: "cutom-loading-name",
  });
};

/**
 * 全局关闭路由删除tag标签
 * @param {*} path 需要删除的路由
 */

export const delViewTag = (path: String) => {
  const tags = store.getState().useMenuStore.tagList;
  const filterTags = tags.filter((item) => item.path !== path);

  store.dispatch(setTagList(filterTags));
};
